import React, { Component, Fragment } from "react";

// antd
import { Dropdown, Menu, Button, Col, Pagination, Form, Input, Tag, Select, Table, Space, notification, Divider, Modal, message, Typography} from "antd";
import {CopyToClipboard} from 'react-copy-to-clipboard';
import { CopyOutlined, CheckOutlined, DownOutlined} from '@ant-design/icons';
import Action from "@c/buttonAction/Index";


// http
import http from '../../../utils/request';
const { Option } = Select;

class CloudRamPoliciy extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "策略名称", dataIndex: "policy_name", key: "policy_name",
                    render: (text, rowData) => {
                        return(
                            <Space direction="vertical">
                                <CopyToClipboard text={rowData.policy_name} 
                                    onCopy={() => 
                                        this.setState({copied: true},
                                        notification.open({
                                            message: '已复制到剪贴板',
                                            icon: <CheckOutlined style={{ color: 'green' }} />,
                                            duration: 2,
                                            placement: 'top',
                                        })
                                    )}
                                >
                                    <span><span style={{marginRight: "5px"}}><CopyOutlined /></span><span style={{color: "#6587FF"}}>{rowData.policy_name}</span></span>
                                </CopyToClipboard>                                 
                            </Space>
                        )
                    }
                },
                {title: "云平台", dataIndex: "cloud-platform", key: "cloud-platform",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.platform}-{rowData.account_name}</Tag>
                            </div>
                        )
                    }
                },
                {title: "策略类型", dataIndex: "policy_type", key: "policy_type",
                    render: (text, rowData) => {
                        return (
                            <Tag color="blue">{rowData.policy_type}</Tag>
                        )
                    }
                },
                {title: "创建时间", dataIndex: "create_date", key: "create_date"},
                {title: "更新时间", dataIndex: "update_date", key: "update_date"},
                {title: "策略版本", dataIndex: "default_version", key: "default_version"},
                {title: "策略描述", dataIndex: "description", key: "description"},
                { 
                    title: "查看", 
                    dataIndex: "operation", 
                    key: "operation", 
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Divider type="vertical"/>
                                <Action>
                                    <Action.Button onClick={() => this.onCatPoliyBtn({rowData: rowData, status: true})}>所有版本</Action.Button>
                                </Action>
                            </div>
                        )
                    }
                },
                { 
                    title: "编辑", 
                    dataIndex: "operation", 
                    key: "operation", 
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Divider type="vertical"/>
                                <Action>
                                    <Action.Button onClick={() => this.onEditPoliyBtn({rowData: rowData, status: true})}>编辑</Action.Button>
                                </Action>
                            </div>
                        )
                    }
                },
                { 
                    title: "删除", 
                    dataIndex: "operation", 
                    key: "operation", 
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Divider type="vertical"/>
                                <Action>
                                    <Action.Button onClick={() => this.onDelPoliyBtn({rowData: rowData, status: true})}>删除</Action.Button>
                                </Action>
                            </div>
                        )
                    }
                }
            ],
            loading: false,
            visible_cat: false, // 用于控制查看弹窗显示
            visible_add: false, // 用于控制添加弹窗显示
            visible_del: false, // 用于控制删除弹窗显示
            visible_edit: false, // 用于控制编辑弹窗显示
            search_account_name: null,
            search_platform: null,
            search_policy_type: null,
            search_create_date: null,
            search_update_date: null,
            search_policy_name: null,
            search_default_version: null,
            search_description: null,
            search_option_account: [],
            search_option_platform: [],
            search_option_policy_name: [],
            search_option_username:[],
            policy_document: '', // 添加状态用于保存 policy_document
            policy_name: '',
            default_version: ''
        }
        this.formRefCat = React.createRef()
        this.formRefAdd = React.createRef()
        this.formRefDel = React.createRef()
        this.formRefEdit = React.createRef()
    }

    // 预加载选项数据
    componentDidMount() {
        this.loadData()
        this.loadDataPlatform()
    }

    loadDataPlatform = () => {
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/cloud/platform', {params: requestData}).then(response=>{
            const search_option_platform = []
            const resp_data = response.data.data.items
            for (let i = 0; i < resp_data.length; i++) {
                search_option_platform.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            this.setState({
                search_option_platform: search_option_platform
            })
        })
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'policy_name__contains': this.state.search_policy_name,
            'platform': this.state.search_platform,
            'account_name': this.state.search_account_name,
            'policy_type': this.state.search_policy_type,
            'create_date': this.state.search_create_date,
            'update_date': this.state.search_update_date,
            'default_version': this.state.search_default_version,
            'description': this.state.search_description
        }
        // 打印 policy_document 数据
        // console.log('loadData :', requestData);
        // 获取分组列表
        http.get('/cloud/ramnew/policies', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    /** 新增自定义策略按钮 */
    onAddPoliyBtn = () => {
        this.setState({
            visible_add: true
        })
    }

    /** 新增自定义策略取消 */
    onFinishAddCancel = () => {
        this.setState({
            visible_add: false
        })
        this.formRefAdd.current.resetFields()
    }

    /** 新增自定义策略提交 */
    onFinishAdd = (data) => {
        const requestData = {
            policy_name: data.policy_name,
            platform: data.platform,
            account_name: data.account_name,
            description: data.description,
            policydocument: data.policy_document,
            type: 'add'
        }
        // console.log('Policy Document:', requestData);
        http.post('/cloud/ramnew/policies', requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_add: false,
            })
            this.formRefAdd.current.resetFields()
            this.loadData()
        }).catch()
    }

    /** 编辑自定义策略按钮 */
    onEditPoliyBtn = async (data) => {
        const requestData = {
            platform: data.rowData.platform,
            account_name: data.rowData.account_name,
            policy_name: data.rowData.policy_name,
            policy_type: data.rowData.policy_type
        }
        http.get('/cloud/ramnew/policies', {params: requestData}).then(response => {
            // 提取 policy_document 并转换为 JSON 字符串
            const policy_document = JSON.stringify(response.data.data.policy_document, null, 2)
            // 打印 policy_document 数据
            // console.log('Policy Document:', policy_document);
            if (this.formRefEdit.current) {
                    this.formRefEdit.current.setFieldsValue({
                        policy_document: policy_document
                    })
                }
            // 将值存储到 state 中
            this.setState({
                platform: data.rowData.platform,
                account_name: data.rowData.account_name,
                policy_name: data.rowData.policy_name,
                default_version: data.rowData.default_version
                })
            })        
            .catch(error => {
                console.error('Error fetching policy details:', error);
            })
        // 显示弹窗
        this.setState({ visible_edit: true })
    }

    /** 编辑自定义策略取消 */
    onFinishEditCancel = () => {
        this.setState({
            visible_edit: false
        })
        this.formRefEdit.current.resetFields()
    }

    /** 编辑自定义策略提交 */
    onFinishEdit = (data) => {
        const requestData = {
            platform: this.state.platform,
            account_name: this.state.account_name,
            policy_name: this.state.policy_name,
            policydocument: data.policy_document,
            type: 'edit'
        }
        // 查看提交参数
        // console.log('Policy Document:', requestData);
        http.post('/cloud/ramnew/policies', requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_edit: false,
            })
            this.formRefEdit.current.resetFields()
            this.loadData()
        }).catch()
    }


    /** 查看授权策略按钮 */
    onCatPoliyBtn = async (data) => {
        const requestData = {
            platform: data.rowData.platform,
            account_name: data.rowData.account_name,
            policy_name: data.rowData.policy_name,
            policy_type: data.rowData.policy_type,
            type: 'list'
        }
        http.post('/cloud/ramnew/policies', requestData).then(response => {
            const policy_document = JSON.stringify(response.data.data, null, 2)
            if (this.formRefCat.current) {
                    this.formRefCat.current.setFieldsValue({
                        policy_document: policy_document
                    });
                }
            })        
            .catch(error => {
                console.error('Error fetching policy details:', error);
            });
        // 显示弹窗
        this.setState({ visible_cat: true })
    }

    /** 关闭查看授权策略 */
    onFinishCatCancel = () => {
        // 关闭弹窗时，设置状态为 false
        this.setState({ visible_cat: false });
    }

    /** 删除自定义策略按钮 */
    onDelPoliyBtn = (data) => {
        // 打印传入的data数据
        // console.log('onDelPoliyBtn called with:', data);
        this.setState({
            visible_del: true,
            platform: data.rowData.platform,
            account_name: data.rowData.account_name,
            login_name: data.rowData.login_name,
            policy_name: data.rowData.policy_name,
            policy_type: data.rowData.policy_type,
            default_version: data.rowData.default_version
        })
    }

    /** 删除自定义策略提交 */
    onFinishDel = async (data) => {
        const requestData = {
            platform: this.state.platform,
            account_name: this.state.account_name,
            policy_name: this.state.policy_name,
            default_version: data.default_version
        }
        // console.log('Policy Document:', requestData);
        http.delete('/cloud/ramnew/policies', { data: requestData }).then(response => {
            message.success(response.data.msg);
            this.setState({
                visible_del: false,
            })
            if (this.formRefDel.current) {
                this.formRefDel.current.resetFields(); 
            }    
            this.loadData()
        }).catch()
    }

    /** 删除自定义策略取消 */
    onFinishDelCancel = () => {
        this.setState({
            visible_del: false
        })
        if (this.formRefDel.current) {
            this.formRefDel.current.resetFields(); // 确保 formRefEdit 存在时才调用
        }    
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 云平台搜索 */
    onFinishSearch = (data) => {
        this.setState({
            page: 1,
            search_policy_name: data.policy_name ? data.policy_name : null,
            search_account_name: data.account_name ? data.account_name : null,
            search_platform: data.platform ? data.platform : null
        })
        this.loadData()
    }

    // 搜索切换云平台
    onChangePlatform = (value) => {
        if (value) {
            this.setState({
                search_instance_platform: value
            })

            const requestData = {
                'page': 1,
                'limit': 1000,
                'platform': value
            }
    
            http.get('/cloud/account', {params: requestData}).then(response=>{
                const search_option_account = []
                const resp_data = response.data.data.items
                for (let i = 0; i < resp_data.length; i++) {
                    search_option_account.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
                }
                this.setState({
                    search_option_account: search_option_account
                })
            })

        } else {
            this.setState({
                search_option_account: '',
            })
        }
    }

    // 按平台账号搜索用户名
    onChangeUsername = (value) => {
        const platform = this.formRefAdd.current.getFieldValue('platform');
        if (value) {
            this.setState({
                search_instance_account_name: value
            })

            const requestData = {
                'page': 1,
                'limit': 1000,
                'account_name': value,
                'platform': platform
            }
            http.get('/cloud/ram/user', {params: requestData}).then(response=>{
                const search_option_username = []
                const resp_data = response.data.data.items
                for (let i = 0; i < resp_data.length; i++) {
                    search_option_username.push(<Option key={resp_data[i].login_name}>{resp_data[i].login_name}</Option>)
                }
                this.setState({
                    search_option_username: search_option_username
                })
            })
        } else {
            this.setState({
                search_option_username: '',
            })
        }
    }

    //按平台账号搜索策略
    onChangePolicy = (value) => {
        const platform = this.formRefAdd.current.getFieldValue('platform');
        const account_name = this.formRefAdd.current.getFieldValue('account_name');
        
        if (value) {
            this.setState({
                search_instance_policy_type: value
            });
    
            // 定义 requestData
            let requestData = {
                'page': 1,
                'limit': 1000,
                'policy_type': value
            };
    
            // 根据不同的 value 修改 requestData
            if (value === 'Custom') {
                requestData['platform'] = platform;
                requestData['account_name'] = account_name;
            }
    
            // 发送请求
            http.get('/cloud/ramnew/policies', { params: requestData }).then(response => {
                const search_option_policy_name = [];
                const resp_data = response.data.data.items;
    
                for (let i = 0; i < resp_data.length; i++) {
                    search_option_policy_name.push(
                        <Option key={resp_data[i].policy_name}>
                            <span>{resp_data[i].policy_name}</span>
                            <br />
                            <span style={{ color: 'gray', fontStyle: 'italic' }}>{resp_data[i].description}</span>
                        </Option>
                    );
                }
    
                // 更新状态
                this.setState({
                    search_option_policy_name: search_option_policy_name
                });
            });
    
        } else {
            this.setState({
                search_option_policy_name: '',
            });
        }
    }
    

    // 搜索云账户
    onChangeAccountName = (value) => {
        this.setState({
            search_account_name: value ? value : null
        })
    }

    render() {
        const { loading, dataSource, columns, page, total, policy_name, default_version, search_option_platform, search_option_account, visible_cat, visible_add, visible_del, visible_edit, policy_document} = this.state;
        const myStyle = { margin: '20px' };
        const myStyle1 = { margin: '10px', float: 'right' };
        // 打印弹窗和policy_document变量详情
        // console.log('Render visible_cat state:', this.state.visible_cat);
        // console.log('Modal policy_document value:', this.formRefCat.current?.getFieldValue('policy_document'));

        const operations = (
            <Menu
                items={[
                    {
                        label: (
                            <Action.Button onClick={() => this.onAddPoliyBtn()}>新增自定义策略</Action.Button>
                        ),
                        key: '0',
                    }
                ]}
            />
        );

        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch} size="small">
                    <Form.Item label="云平台" name="platform">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择区域"
                            optionFilterProp="children"
                            onChange={this.onChangePlatform}
                            filterOption={(input, option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {search_option_platform}
                        </Select>
                    </Form.Item>

                    <Form.Item label="云账户" name="account_name">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择云账户"
                            onChange={this.onChangeAccountName}
                        >
                            {search_option_account}
                        </Select>                      
                    </Form.Item>

                    <Form.Item label="策略名称" name="policy_name">
                        <Input placeholder="请输入策略名称" />
                    </Form.Item>

                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>
                <div style={myStyle1}>
                    <Dropdown overlay={operations}>
                        <Action.Button>
                            <Space>
                                更多操作
                                <DownOutlined />
                            </Space>
                        </Action.Button>
                    </Dropdown>
                </div>

                <div style={myStyle1}></div>
                <div>
                    <Table
                        pagination={false}
                        rowKey="id"
                        columns={columns}
                        dataSource={dataSource}
                        loading={loading}
                        scroll={{ y: 500, x: '70vw' }}
                    />
                </div>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Modal
                    title="查看自定义策略"
                    open={visible_cat} // 绑定弹窗显示状态
                    onCancel={this.onFinishCatCancel}
                    footer={null}
                    width={800} // 设置宽度为 800px，可以根据需要调整
                    style={{ top: 40}} // 可以设置 Modal 的位置（距离顶部的距离）
                >
                    <Form
                        ref={this.formRefCat}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <Form.Item label="策略内容" name="policy_document">
                        <Input.TextArea
                            rows={20}
                            value={policy_document} // Set the value from state
                            readOnly
                            style={{ width: '100%' }}
                            placeholder="策略内容将显示在这里"
                        />
                        </Form.Item>
                    </Form>           
                </Modal>

                <Modal
                    title="编辑自定义策略"
                    open={visible_edit} // 绑定弹窗显示状态
                    onCancel={this.onFinishEditCancel}
                    footer={null}
                    width={800} // 设置宽度为 800px，可以根据需要调整
                    style={{ top: 40}} // 可以设置 Modal 的位置（距离顶部的距离）
                >
                    <Form
                        onFinish={this.onFinishEdit}
                        ref={this.formRefEdit}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <Form.Item label="策略版本" name="default_version">
                            <Typography.Text>{default_version}</Typography.Text>
                        </Form.Item>  
                        <Form.Item label="策略内容" name="policy_document" rules={[{ required: true, message: '请输入策略内容'},
                                {
                                    validator: (_, value) => {
                                        try {
                                            const parsed = JSON.parse(value); // 尝试解析 JSON
                                            if (typeof parsed === 'object' && parsed !== null) {
                                                return Promise.resolve(); // 如果是对象或数组，校验通过
                                            } else {
                                                return Promise.reject('请输入有效的 JSON 对象或数组'); // 如果不是对象或数组，提示错误
                                            }
                                        } catch (error) {
                                            return Promise.reject('请输入有效的 JSON 格式'); // 如果解析失败，提示错误
                                        }
                                    }
                                }]}
                        >
                        <Input.TextArea
                            rows={20}
                            value={policy_document} // Set the value from state
                            style={{ width: '100%' }}
                            placeholder="策略内容将显示在这里"
                        />
                        </Form.Item>
                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>     
                    </Form>           
                </Modal>

                <Modal
                    title="新增自定义策略"
                    open={visible_add}
                    onCancel={this.onFinishAddCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width="700px"
                >
                    <Form
                        onFinish={this.onFinishAdd}
                        ref={this.formRefAdd}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <Form.Item label="云平台名称" name="platform" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择云平台"
                                onChange={this.onChangePlatform}
                                >
                                {search_option_platform}
                            </Select>
                        </Form.Item>

                        <Form.Item label="云账户名称" name="account_name" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                onChange={this.onChangeUsername}
                                placeholder="选择云账户"
                                >
                                {search_option_account}
                            </Select>
                        </Form.Item>

                        <Form.Item label="策略名称" name="policy_name" rules={[{ required: true}]}>
                            <Input></Input>
                        </Form.Item>
                        <Form.Item label="策略描述" name="description" rules={[{ required: true, message: '请输入策略描述'}]}>
                            <Input></Input>
                        </Form.Item>
                        <Form.Item label="策略内容" name="policy_document" rules={[{ required: true, message: '请输入策略内容'},
                                {
                                    validator: (_, value) => {
                                        try {
                                            const parsed = JSON.parse(value); // 尝试解析 JSON
                                            if (typeof parsed === 'object' && parsed !== null) {
                                                return Promise.resolve(); // 如果是对象或数组，校验通过
                                            } else {
                                                return Promise.reject('请输入有效的 JSON 对象或数组'); // 如果不是对象或数组，提示错误
                                            }
                                        } catch (error) {
                                            return Promise.reject('请输入有效的 JSON 格式'); // 如果解析失败，提示错误
                                        }
                                    }
                                }
                            ]}
                        >
                            <Input.TextArea rows={12} />
                        </Form.Item>
                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="删除自定义授权指定版本"
                    open={visible_del}
                    onCancel={this.onFinishDelCancel}
                    footer={null}
                    okText="确认"
                    cancelText="取消"
                >
                    <Form
                        onFinish={this.onFinishDel}
                        ref={this.formRefEdit}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <p>请输入删除自定义策略<span style={{color: 'red'}}>{policy_name}的版本号</span> </p>
                        <Form.Item label="版本号" name="default_version" rules={[{ required: false}]}>
                                <Input></Input>
                        </Form.Item>
                        <Form.Item>
                                <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>   
                    </Form>            
                </Modal>

            </Fragment>
        )
    }
}
export default CloudRamPoliciy


